package remote.service;

import client.common.result.Result;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import remote.common.constant.UrlConstant;
import remote.utils.FileUtil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 版本控制服务
 */
public interface VersionService {
    /**
     * 检查版本
     *
     * @return 版本检查结果 ：版本需要更新返回200
     */
    default Result checkVersion(String currentVersion) {
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("currentVersion", currentVersion);
        String resultStr = HttpRequest.get(UrlConstant.VERSION_URL + "/version/checkVersion")
                .form(requestParams)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    
    /**
     * 获取最新版本
     *
     * @return 最新版本
     */
    default String getNewVersion() {
        // 获取当前应用程序的目录
        String saveDirectory = System.getProperty("user.dir");
        HttpResponse response = HttpRequest.get(UrlConstant.VERSION_URL + "/version/downloadVersion")
                .execute();
        String header = response.header("Content-Disposition");
        String fileName = FileUtil.getFileNameFromDisposition(header);
        String savePath = saveDirectory + "/" + fileName;
        // 保存下载的文件
        try (InputStream in = response.bodyStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            IoUtil.copy(in, out); // 使用 Hutool 的 IoUtil 工具类
            System.out.println("文件下载成功，保存路径：" + savePath);
            
        } catch (FileNotFoundException e) {
            throw new RuntimeException("保存文件失败: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException("IO 错误: " + e.getMessage(), e);
        }
        return fileName;
    }
    
    
}
